
import axios from "axios";
import { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
import Msg from './TextReply';

function CommtensMilde({id}:any) {
    const yid = useLocation().state;
    console.log(yid,'tttttt')
    const [com, setCom] = useState<string>("");
    const [list, setList] = useState<{ coid: number, nickname: string, avatar: string, content: string, addtimes: any }[]>([]);
    useEffect(function () {
        getContext();
    }, [])

    //向数据库提交评论内容
    async function saveAcomments() {
        let content = com;//评论类容
        //后端使用人session
        let dynamicid = yid ; //对应文章的id
        let uid =sessionStorage.getItem('uid')
        console.log(uid);
        let res = await axios.post('http://127.0.0.1:81/saveAcomments', {
            content: content,
           dynamicid,
           uid
        })
        return res.data;
    }
    //获取相关评论的内容
    function getContext() {
        let id=yid 
        console.log(id);
        
        axios.get('http://127.0.0.1:81/getContext', {
            params: { id }
        })
            .then(function (res) {
                console.log(res.data.results);
                setList(res.data.results);
            })
            .catch(function (error) {
                console.log(error);
            });
    }
    //对时间的处理
    function timeTrans(timess: any) {
        return timess.toString().substring(0, 10);

    }
    async function send() {
        if (com.trim() == '') {
            alert('请输入你的相关评论')
        } else {
            let r = await saveAcomments()
            setCom("");
            getContext();
        }
    }
    return (
        <div>
            <div>
                <textarea value={com} placeholder="回复楼主..." className="textC" onChange={(e: any) => { setCom(e.target.value) }}></textarea>
                <div className="SenC" onClick={send}>发送</div>
                <div className="commList">
                    {
                        list.map((item, i) => {

                            return (
                                <Msg key={item.coid} url={item.avatar} username={item.nickname} inf={item.content} addtimes={timeTrans(item.addtimes)} />
                            )
                        })
                    }
                    <div className="noMore">没有更多了</div>
                </div>
            </div>
        </div>
    )
}
export default CommtensMilde;